﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragCard : BasicCard, IDragHandler, IEndDragHandler, IPointerEnterHandler, IPointerExitHandler
{
    private PlayerProxier _playerProxier;

    private Quaternion m_setRotateAngle;
    private int belongIndex;

    private CardAnimationController _animationController;
    
    private bool isHover;

    private Vector3 deckPosition;
    
    private void Start()
    {
        _animationController = GetComponent<CardAnimationController>();
    }

    public void SetPlayerProxier(PlayerProxier playerProxier)
    {
        _playerProxier = playerProxier;
    }
    
    #region 鼠标拖动事件
    public void OnDrag(PointerEventData data)
    {
        ShowTargetGridAtMousePosition();
        caller.isHoldingCard = true;
        
        TileManager.ShowAttackRange(GameObject.FindGameObjectWithTag(StaticDataManager.PLAYER_TAG), pairData.cardData.range, pairData.cardData.rangeType, StaticDataManager.TILE_TAG);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        HideTargetGrid();
        TileManager.HideAllTileOverlay();
        
        caller.isHoldingCard = false;

        // 这边的话是因为 drag的话是只能给player用的 所以这个时候是要以player的身份来扔卡
        if (ExecuteCard())
        {
            _playerProxier.DiscardCardInstance(gameObject, belongDeckType);
        }
        
        TileManager.ShowSelectableTiles();
    }

    #endregion
    
    #region 鼠标悬停事件
    public void OnPointerEnter(PointerEventData eventData)
    {
        if (!DOTween.IsTweening(transform))
        {
            deckPosition = transform.position;     
        }
        m_setRotateAngle = gameObject.transform.rotation;
       
        
        belongIndex = GetComponent<RectTransform>().GetSiblingIndex();
        
        GetComponent<RectTransform>().SetAsLastSibling();
        
        _animationController.PlayCardAnimation(GetHoverAnimationSet());
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        gameObject.transform.localScale = Vector3.one;
        gameObject.transform.rotation = m_setRotateAngle;
        
        GetComponent<RectTransform>().SetSiblingIndex(belongIndex);
        
        _animationController.PlayCardAnimation(GetDeckAnimationSet());
    }

    public AnimationSet GetDeckAnimationSet()
    {
        var newPos = gameObject.transform.position;
        newPos.y -= 100f;
        
        return new AnimationSet()
        {
            pos = deckPosition,
            scale = Vector3.one,
            rot = m_setRotateAngle,
        };
    }

    public AnimationSet GetHoverAnimationSet()
    {
        var newPos = gameObject.transform.position; 
        newPos.y += 100f;
        
        return new AnimationSet()
        {
            pos = newPos,
            rot = Quaternion.identity,
            scale = new Vector3(1.3f, 1.3f, 1.3f)
        };
    }
    #endregion
}
